package com.masteringwave;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;

import com.google.wave.api.*;

@SuppressWarnings("serial")
public class WorkflowServlet extends AbstractRobotServlet {

	public static final String AMOUNT_FIELD = "AMOUNT_FIELD";
	public static final String NAME_FIELD = "NAME_FIELD";
	public static final String APPROVE_BUTTON = "APPROVE_BUTTON";
	public static final String REJECT_BUTTON = "REJECT_BUTTON";
	Cache cache;
	public WorkflowServlet(){
		super();
		

        try {
            cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
        } catch (CacheException e) {
            //
        }

	}
	
	@Override
	public void processEvents(RobotMessageBundle bundle) {
		Wavelet wavelet = bundle.getWavelet();
		String creator = wavelet.getCreator();
		if (bundle.wasSelfAdded()) {

			Blip blip = wavelet.appendBlip();
			TextView textView = blip.getDocument();
			textView.appendMarkup("<p><b>Welcome to the First Wave Bank</b></p>");
			textView.append("\nDescribe what you want to borrow to in the wave.  \n");
			textView.append("Then fill out the form for your information\n");
			FormView form = textView.getFormView();
			form.append(new FormElement(ElementType.LABEL, "labelname",
					"Your name"));
			form.append(new FormElement(ElementType.INPUT, NAME_FIELD));
			textView.append("\n");
			form.append(new FormElement(ElementType.LABEL, "labelamount",
					"Borrow amount in $"));
			form.append(new FormElement(ElementType.INPUT, AMOUNT_FIELD));
			form.append(new FormElement(ElementType.BUTTON, "submit", "Apply"));
			
		}

		for (Event e : bundle.getEvents()) {
			if (e.getType() == EventType.BLIP_SUBMITTED) {
				// get event blip
				Blip blip = e.getBlip();
				TextView textView = blip.getDocument();

			}
			if (e.getType() == EventType.FORM_BUTTON_CLICKED) {
				
				Blip blip = e.getBlip();
				
				FormView form = blip.getDocument().getFormView();
				FormElement name = form.getFormElement(NAME_FIELD);
				FormElement amount = form.getFormElement(AMOUNT_FIELD);
				FormElement reject = form.getFormElement(REJECT_BUTTON);
				FormElement approve = form.getFormElement(APPROVE_BUTTON);
				if (name != null) {
					// we are in the application form.
					String errorMessage = "";
					if (name.getValue() == null
							|| name.getValue().trim().length() == 0) {
						errorMessage += "Please enter name:\n";
					}
					if (amount.getValue() == null
							|| amount.getValue().trim().length() == 0) {
						errorMessage += "Please enter amount:\n";
					}else {
						try{
						BigDecimal bd = new BigDecimal(amount.getValue());
						}catch(Exception bdException ){
							errorMessage+="Amount: "+ amount.getValue()+" is not a number";
						}
						
					}
					
					if (errorMessage.length() > 0) {

						blip.getDocument().appendStyledText(
								new StyledText("\n" + errorMessage,
										StyleType.BOLD));
					} else {
						blip.getDocument().appendStyledText(
								new StyledText("\nSubmitted for appr" +
										"oval",
										StyleType.BOLD));
						createApproveForm(wavelet);
						// save name and amount
						cache.put(wavelet.getWaveId()+"name", name.getValue());
						cache.put(wavelet.getWaveId()+"amount", amount.getValue());

					}
				}else{
					// We are in the Approve/Reject tab.
					// validate the the user is not trying to validate his own application
					if(e.getModifiedBy().equals(wavelet.getCreator())){
						blip.getDocument().appendStyledText(
								new StyledText("\nYou cannot approve your own application",
										StyleType.BOLD));
					}else{
						
						Blip resultBlip = wavelet.appendBlip();
					   // check if hte approve button is pressed. 
						if(approve.getValue().equalsIgnoreCase("clicked")){
						 String nameReturn =(String)cache.get(wavelet.getWaveId()+"name");
						 String amountReturn = (String)	cache.get(wavelet.getWaveId()+"amount");
						   resultBlip.getDocument().append("Application approved. "+nameReturn+" will receive your $"+amountReturn+ " soon");
					   }
					   if(reject.getValue().equalsIgnoreCase("clicked")){
						   resultBlip.getDocument().append("Application rejected. ");
					   }
					}
				}

			}

		}

	}

	private void createApproveForm(Wavelet wavelet) {
		Blip blip = wavelet.appendBlip();
		TextView textView = blip.getDocument();
		textView
				.appendMarkup("<p><b>Please approve or rejct the appliction</b></p>");
		textView.append("\n");
		FormView form = textView.getFormView();

		form.append(new FormElement(ElementType.BUTTON, REJECT_BUTTON, "Reject"));

		form.append(new FormElement(ElementType.BUTTON, APPROVE_BUTTON, "Approve"));

		String[] creator = wavelet.getCreator().split("@");
		// ok maybe not the best way to find the approver. 
		String approver = creator[0] + "-test@" + creator[1];
		wavelet.addParticipant(approver);
	}

	public List getAllAppspot(List participant) {
		List appspot = new ArrayList();
		Iterator iterar = participant.iterator();
		while (iterar.hasNext()) {
			String iter = (String) iterar.next();
			int mid = iter.lastIndexOf("@");
			String ext = iter.substring(mid + 1, iter.length());
			if (ext.equals("appspot.com")) {
				appspot.add(iter);
				System.out.println(iter);
			}
		}
		return appspot;
	}

}